package com.study.system.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.study.system.order.config.TimeoutOrderMQConfig;
import com.study.system.order.entity.UserCourseOrder;
import com.study.system.order.service.OrderService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 超时订单监听器
 */
@Component
public class TimeoutOrderListener {

    private Logger logger = LoggerFactory.getLogger(TimeoutOrderListener.class);

    @Resource
    private OrderService orderService;

    /**
     * 死信队列的监听器（消费者）
      * @param tradeNo
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = TimeoutOrderMQConfig.DEADLETTER_ORDER_QUEUE,durable = "true"),
            exchange = @Exchange(value = TimeoutOrderMQConfig.DEADLETTER_ORDER_EXCHANGE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = TimeoutOrderMQConfig.DEADLETTER_ORDER_QUEUE_KEY
    ))
    public void handleTimeoutOrder(String tradeNo, Channel channel, Message message){
        logger.info("收到超时订单：{}",tradeNo);
        try {
            //查询订单
            UserCourseOrder order =
                    orderService.getOne(new QueryWrapper<UserCourseOrder>().lambda().eq(UserCourseOrder::getTradeNo, tradeNo));
            //判断订单如果没有支付,就改为取消状态
            if (order.getStatus() == 0) {
                order.setStatus(2);
                orderService.update(order, new QueryWrapper<UserCourseOrder>().lambda().eq(UserCourseOrder::getTradeNo, tradeNo));
                logger.info("取消超时订单：{}", tradeNo);
            }
            //手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception ex){
            logger.error("超时订单处理出现异常",ex);
        }
    }
}
